<template>
  <div class="chat-login">
    <div class='login-box'>
      <div class='login-form'>
          <div class='form'>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
              <el-form-item label="昵称" prop="name">
                <el-input v-model="ruleForm.name" placeholder="差不多只能显示这么长"></el-input>
              </el-form-item>
              <el-form-item label="信号" >
                <el-input v-model="ruleForm.wechat" placeholder='方便私聊，私聊个鬼（选填）'></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="login('ruleForm')">走你</el-button>
              </el-form-item>
            </el-form>
          </div>
      </div>
    </div>
  </div>
</template>

<script>
import Chat from '../api/client'
export default {
  name: 'chat-login',
  data () {
    return {
      name: '',
      wechat: '',
      uid: '',
      ruleForm: {
        name: '',
        wechat: '',
        uid: ''
      },
      rules: {
        name: [
          {required: true, message: '咳咳，不知英雄如何称呼？', trigger: 'blur'},
          {min: 1, max: 10, message: '只能显示这么多个字哦 (1-10)', trigger: 'blur'}
        ]
      }
    }
  },
  mounted () {
    this.$nextTick(function () {
      if (localStorage.name) {
        this.$router.push({path: '/room', query: {refresh: true}})
      }
    })
  },
  methods: {
    login (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm.name)
          // 获取id，名字+随机数
          this.ruleForm.uid = this.ruleForm.name + '_' + Math.ceil(Math.random() * 10000)
          this.ruleForm.name = this.ruleForm.name.slice(0, 10)
          console.log(this.ruleForm.uid)
          if (localStorage) {
            localStorage.setItem('name', this.ruleForm.name)
            localStorage.setItem('wechat', this.ruleForm.wechat)
            localStorage.setItem('uid', this.ruleForm.uid)
          }
          Chat.init()
          this.ruleForm.name = ''
          this.ruleForm.wechat = ''
          this.ruleForm.uid = ''
          this.$router.push({path: '/room', query: {refresh: true}})
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.chat-login{
  background: url(../assets/img/mei.jpg) no-repeat scroll 30% 50%;
  background-size: cover;
  position:absolute;
  top:0;left:0;bottom:0;right:0;
}
.login-box{
  display:table;
  height:100%;
  width:90%;
  max-width:400px;
  margin:0 auto 0;
}
.login-form{
  display:table-cell;
  vertical-align:middle;
}
.el-form-item{
  margin:0;
  padding:5px 20px;
}
.el-button.el-button--primary{
  margin:10px 0 0;
}
.form{
  padding:10px;
  text-align:center;
  background:rgba(255, 255, 255, 0.75)
}
</style>
